<template>
  <div class="purchase-order-detail-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="nav-content">
        <div class="nav-left">
          <h1 class="nav-title">
            <span class="title-icon">📋</span>
            采购订单详情
            <el-tag v-if="order" :type="getStatusTagType(order.status)" class="status-tag">
              {{ order.status }}
            </el-tag>
          </h1>
        </div>
        <div class="nav-right">
          <div class="nav-actions">
            <el-button @click="goBack">返回列表</el-button>
            <el-button 
              v-if="canEdit" 
              type="warning" 
              @click="editOrder"
            >
              编辑
            </el-button>
            <el-button 
              v-if="canSubmit" 
              type="primary" 
              @click="submitForApproval"
            >
              提交审批
            </el-button>
            <el-button 
              v-if="canWithdraw" 
              type="info" 
              @click="withdrawOrder"
            >
              撤回
            </el-button>
            <el-button 
              v-if="canApprove" 
              type="success" 
              @click="showApprovalDialog"
            >
              审批
            </el-button>
            <el-dropdown v-if="hasMoreActions">
              <el-button type="info">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="printOrder">打印</el-dropdown-item>
                  <el-dropdown-item @click="exportOrder">导出</el-dropdown-item>
                  <el-dropdown-item divided @click="copyOrder">复制订单</el-dropdown-item>
                  <el-dropdown-item v-if="canDelete" @click="deleteOrder">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content" v-loading="loading">
      <div v-if="order" class="order-content">
        <!-- 基本信息卡片 -->
        <div class="info-card">
          <div class="card-header">
            <span class="card-title">📋 基本信息</span>
          </div>
          <div class="card-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">订单号：</span>
                  <span class="value">{{ order.orderNumber }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">订单类型：</span>
                  <el-tag :type="getOrderTypeTagType(order.orderType)">
                    {{ order.orderType }}
                  </el-tag>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">优先级：</span>
                  <el-tag :type="getPriorityTagType(order.priority)">
                    {{ order.priority }}
                  </el-tag>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span class="value">{{ formatDateTime(order.createTime) }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">创建人：</span>
                  <span class="value">{{ order.creator }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">更新时间：</span>
                  <span class="value">{{ formatDateTime(order.updateTime) }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">预计交货日期：</span>
                  <span class="value">{{ formatDate(order.expectedDeliveryDate) }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">订单金额：</span>
                  <span class="value amount">¥{{ formatCurrency(order.totalAmount) }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 供应商信息卡片 -->
        <div class="info-card">
          <div class="card-header">
            <span class="card-title">🏢 供应商信息</span>
          </div>
          <div class="card-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">供应商名称：</span>
                  <span class="value">{{ order.supplierName }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">联系人：</span>
                  <span class="value">{{ order.supplierContact }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span class="value">{{ order.supplierPhone }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">电子邮箱：</span>
                  <span class="value">{{ order.supplierEmail }}</span>
                </div>
              </el-col>
              <el-col :span="16">
                <div class="info-item">
                  <span class="label">供应商地址：</span>
                  <span class="value">{{ order.supplierAddress }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 关联信息卡片 -->
        <div class="info-card" v-if="order.salesOrderNumber || order.requisitionNumber">
          <div class="card-header">
            <span class="card-title">🔗 关联信息</span>
          </div>
          <div class="card-content">
            <el-row :gutter="20">
              <el-col :span="12" v-if="order.salesOrderNumber">
                <div class="info-item">
                  <span class="label">关联销售订单：</span>
                  <el-link type="primary" @click="viewSalesOrder(order.salesOrderId)">
                    {{ order.salesOrderNumber }}
                  </el-link>
                </div>
              </el-col>
              <el-col :span="12" v-if="order.requisitionNumber">
                <div class="info-item">
                  <span class="label">关联请购单：</span>
                  <el-link type="primary" @click="viewRequisition(order.requisitionId)">
                    {{ order.requisitionNumber }}
                  </el-link>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 采购明细卡片 -->
        <div class="info-card">
          <div class="card-header">
            <span class="card-title">📦 采购明细</span>
          </div>
          <div class="card-content">
            <el-table :data="order.items" border style="width: 100%">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="materialName" label="物料名称" min-width="200" />
              <el-table-column prop="specification" label="规格型号" width="150" />
              <el-table-column prop="unit" label="单位" width="80" />
              <el-table-column prop="quantity" label="数量" width="100" align="right">
                <template #default="{ row }">
                  {{ formatNumber(row.quantity) }}
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" label="单价" width="120" align="right">
                <template #default="{ row }">
                  ¥{{ formatCurrency(row.unitPrice) }}
                </template>
              </el-table-column>
              <el-table-column prop="totalAmount" label="金额" width="120" align="right">
                <template #default="{ row }">
                  <span class="amount">¥{{ formatCurrency(row.totalAmount) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注" min-width="150" />
            </el-table>
            
            <!-- 汇总信息 -->
            <div class="summary-section">
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="summary-item">
                    <span class="label">总数量：</span>
                    <span class="value">{{ totalQuantity }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="summary-item">
                    <span class="label">明细项数：</span>
                    <span class="value">{{ order.items?.length || 0 }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="summary-item">
                    <span class="label">订单总金额：</span>
                    <span class="value amount">¥{{ formatCurrency(order.totalAmount) }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>

        <!-- 附加信息卡片 -->
        <div class="info-card">
          <div class="card-header">
            <span class="card-title">📝 附加信息</span>
          </div>
          <div class="card-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">付款方式：</span>
                  <span class="value">{{ order.paymentMethod }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">付款条件：</span>
                  <span class="value">{{ order.paymentTerms }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="info-item">
                  <span class="label">运输方式：</span>
                  <span class="value">{{ order.shippingMethod }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="info-item">
                  <span class="label">交货地址：</span>
                  <span class="value">{{ order.deliveryAddress }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="order.remarks">
              <el-col :span="24">
                <div class="info-item">
                  <span class="label">备注说明：</span>
                  <div class="remarks-content">{{ order.remarks }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 审批流程卡片 -->
        <div class="info-card">
          <div class="card-header">
            <span class="card-title">🔄 审批流程</span>
            <el-button size="small" @click="refreshApprovalFlow">刷新</el-button>
          </div>
          <div class="card-content">
            <div v-if="!approvalFlow || !approvalFlow.approvalRecords || approvalFlow.approvalRecords.length === 0" class="no-approval-data">
              <el-empty description="暂无审批记录" />
            </div>
            <el-timeline v-else>
              <el-timeline-item
                v-for="record in approvalFlow.approvalRecords"
                :key="record.id"
                :timestamp="formatDateTime(record.approvalTime)"
                :type="getApprovalTimelineType(record.decision)"
                placement="top"
              >
                <div class="approval-record">
                  <div class="approval-header">
                    <span class="approver">{{ record.approverName }}</span>
                    <span class="role">{{ record.approverRole }}</span>
                    <el-tag :type="getApprovalDecisionType(record.decision)" size="small">
                      {{ getApprovalDecisionText(record.decision) }}
                    </el-tag>
                  </div>
                  <div class="approval-content" v-if="record.approvalComments">
                    <span class="comments">{{ record.approvalComments }}</span>
                  </div>
                  <div class="approval-footer">
                    <span class="status-change">
                      {{ record.statusBefore }} → {{ record.statusAfter }}
                    </span>
                    <span class="duration">
                      处理用时：{{ record.processingDurationMinutes }}分钟
                    </span>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
    </div>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialog.visible"
      title="审批采购订单"
      width="500px"
      @close="closeApprovalDialog"
    >
      <el-form :model="approvalDialog.form" label-width="80px">
        <el-form-item label="审批决定">
          <el-radio-group v-model="approvalDialog.form.decision">
            <el-radio value="通过">同意</el-radio>
                          <el-radio value="驳回">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalDialog.form.comments"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeApprovalDialog">取消</el-button>
          <el-button type="primary" @click="submitApproval" :loading="submitting">
            确认审批
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { usePurchaseOrderStore } from '@/stores/purchaseOrder'
import type { PurchaseOrderExtendedDto, ApprovalFlowDto, ApprovalDecisionDto } from '@/types/console'

// 路由
const route = useRoute()
const router = useRouter()

// 状态管理
const purchaseOrderStore = usePurchaseOrderStore()

// 响应式数据
const loading = ref(true)
const submitting = ref(false)
const order = ref<PurchaseOrderExtendedDto>()
const approvalFlow = ref<ApprovalFlowDto>()

// 获取订单ID
const orderId = computed(() => Number(route.params.id))

// 审批对话框
const approvalDialog = reactive({
  visible: false,
  form: {
    decision: '通过',
    comments: ''
  }
})

// 计算属性
const totalQuantity = computed(() => {
  return order.value?.items?.reduce((sum, item) => sum + (item.quantity || 0), 0) || 0
})

// 权限判断
const canEdit = computed(() => {
  return order.value && ['草稿', '已拒绝'].includes(order.value.status)
})

const canSubmit = computed(() => {
  return order.value && order.value.status === '草稿'
})

const canWithdraw = computed(() => {
  return order.value && order.value.status === '待审批'
})

const canApprove = computed(() => {
  return order.value && ['待审批', '审批中'].includes(order.value.status)
})

const canDelete = computed(() => {
  return order.value && ['草稿', '已拒绝'].includes(order.value.status)
})

const hasMoreActions = computed(() => {
  return true // 总是显示更多操作，包含打印、导出等
})

// 生命周期
onMounted(async () => {
  await loadOrderData()
  await loadApprovalFlow()
})

// 方法
const loadOrderData = async () => {
  loading.value = true
  try {
    const result = await purchaseOrderStore.getPurchaseOrderExtendedDetail(orderId.value)
    if (result.code === 200 && result.data) {
      order.value = result.data
    } else {
      ElMessage.error(result.msg || '加载订单数据失败')
      goBack()
    }
  } catch (error) {
    ElMessage.error('加载订单数据失败')
    goBack()
  } finally {
    loading.value = false
  }
}

const loadApprovalFlow = async () => {
  try {
    const result = await purchaseOrderStore.fetchApprovalFlow(orderId.value)
    if (result.code === 200 && result.data) {
      approvalFlow.value = result.data
    }
  } catch (error) {
    console.error('加载审批流程失败:', error)
  }
}

const refreshApprovalFlow = () => {
  loadApprovalFlow()
}

// 操作方法
const goBack = () => {
  router.push('/main/procurement/purchase-order')
}

const editOrder = () => {
  router.push(`/main/procurement/purchase-order/${orderId.value}/edit`)
}

const submitForApproval = async () => {
  try {
    await ElMessageBox.confirm('确认提交该采购订单进行审批？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await purchaseOrderStore.submitForApproval(orderId.value)
    ElMessage.success('提交成功')
    await loadOrderData()
    await loadApprovalFlow()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('提交失败')
    }
  }
}

const withdrawOrder = async () => {
  try {
    await ElMessageBox.confirm('确认撤回该采购订单？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await purchaseOrderStore.withdrawOrder(orderId.value)
    ElMessage.success('撤回成功')
    await loadOrderData()
    await loadApprovalFlow()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('撤回失败')
    }
  }
}

const showApprovalDialog = () => {
  approvalDialog.visible = true
  approvalDialog.form = {
    decision: '通过',
    comments: ''
  }
}

const closeApprovalDialog = () => {
  approvalDialog.visible = false
}

const submitApproval = async () => {
  submitting.value = true
  try {
    const decision: ApprovalDecisionDto = {
      decision: approvalDialog.form.decision,
      comments: approvalDialog.form.comments,
      attachmentUrls: []
    }
    
    await purchaseOrderStore.approveOrder(orderId.value, decision)
    ElMessage.success('审批成功')
    closeApprovalDialog()
    await loadOrderData()
    await loadApprovalFlow()
  } catch (error) {
    ElMessage.error('审批失败')
  } finally {
    submitting.value = false
  }
}

const deleteOrder = async () => {
  try {
    await ElMessageBox.confirm('确认删除该采购订单？删除后不可恢复！', '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    await purchaseOrderStore.deletePurchaseOrder(orderId.value)
    ElMessage.success('删除成功')
    goBack()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 更多操作
const printOrder = () => {
  window.print()
}

const exportOrder = () => {
  ElMessage.info('导出功能开发中...')
}

const copyOrder = () => {
  router.push(`/main/procurement/purchase-order/create?copy=${orderId.value}`)
}

// 关联数据查看
const viewSalesOrder = (id?: number) => {
  if (id) {
    router.push(`/sales-order/${id}`)
  }
}

const viewRequisition = (id?: number) => {
  if (id) {
    router.push(`/requisition/${id}`)
  }
}

// 工具方法
const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatDate = (date: string | undefined) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const formatNumber = (num: number) => {
  // 移除多余的小数位，保留最多4位小数，但去掉末尾的0
  return parseFloat(num.toFixed(4)).toLocaleString('zh-CN')
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '草稿': 'info',
    '待审批': 'warning',
    '审批中': 'primary',
    '已审批': 'success',
    '已拒绝': 'danger',
    '已撤回': 'info'
  }
  return typeMap[status] || 'info'
}

const getOrderTypeTagType = (orderType: string) => {
  const typeMap: Record<string, string> = {
    '标准采购': '',
    '紧急采购': 'danger',
    '框架采购': 'success',
    '补充采购': 'warning'
  }
  return typeMap[orderType] || ''
}

const getPriorityTagType = (priority: string | undefined) => {
  if (!priority) return ''
  const typeMap: Record<string, string> = {
    '低': 'info',
    '中': '',
    '高': 'warning',
    '紧急': 'danger'
  }
  return typeMap[priority] || ''
}

const getApprovalTimelineType = (decision: string) => {
  const typeMap: Record<string, string> = {
    '提交': 'primary',
    '同意': 'success',
    '拒绝': 'danger',
    '撤回': 'warning'
  }
  return typeMap[decision] || 'primary'
}

const getApprovalDecisionType = (decision: string) => {
  const typeMap: Record<string, string> = {
    '提交': 'primary',
    '同意': 'success',
    '拒绝': 'danger',
    '撤回': 'warning'
  }
  return typeMap[decision] || 'primary'
}

const getApprovalDecisionText = (decision: string) => {
  const textMap: Record<string, string> = {
    'submit': '提交',
    '通过': '同意',
    '驳回': '拒绝',
    'withdraw': '撤回'
  }
  return textMap[decision] || decision
}
</script>

<style scoped>
.purchase-order-detail-page {
  min-height: 100vh;
  background: #ffffff;
  position: relative;
}

.top-navbar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-left .nav-title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.title-icon {
  font-size: 1.8rem;
}

.status-tag {
  margin-left: 1rem;
}

.nav-actions {
  display: flex;
  gap: 0.5rem;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 2rem;
}

.info-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  margin-bottom: 1.5rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  background: #409eff;
  color: white;
  padding: 1rem 1.5rem;
  font-size: 1.1rem;
  font-weight: 600;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.card-content {
  padding: 1.5rem;
}

.info-item {
  margin-bottom: 1rem;
}

.info-item .label {
  font-weight: 600;
  color: #606266;
  margin-right: 0.5rem;
}

.info-item .value {
  color: #303133;
}

.amount {
  color: #67c23a;
  font-weight: 600;
}

.remarks-content {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 0.75rem;
  margin-top: 0.5rem;
  white-space: pre-wrap;
}

.summary-section {
  margin-top: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.summary-item {
  text-align: center;
  padding: 0.5rem;
}

.summary-item .label {
  font-size: 0.9rem;
  color: #666;
  display: block;
  margin-bottom: 0.25rem;
}

.summary-item .value {
  font-size: 1.2rem;
  font-weight: 600;
  color: #2c3e50;
  display: block;
}

.approval-record {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 0.5rem;
}

.approval-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.approver {
  font-weight: 600;
  color: #303133;
}

.role {
  color: #909399;
  font-size: 0.875rem;
}

.approval-content {
  margin: 0.5rem 0;
}

.comments {
  color: #606266;
  font-style: italic;
}

.approval-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.875rem;
  color: #909399;
  margin-top: 0.5rem;
}

.status-change {
  color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-content {
    padding: 1rem;
    flex-direction: column;
    gap: 1rem;
  }

  .main-content {
    padding: 1rem;
  }

  .nav-actions {
    width: 100%;
    justify-content: center;
    flex-wrap: wrap;
  }

  .card-content {
    padding: 1rem;
  }

  .approval-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.25rem;
  }
}

/* 打印样式 */
@media print {
  .top-navbar,
  .nav-actions {
    display: none !important;
  }

  .purchase-order-detail-page {
    background: white !important;
  }

  .info-card {
    background: white !important;
    box-shadow: none !important;
    border: 1px solid #ddd !important;
    break-inside: avoid;
  }

  .card-header {
    background: #f5f5f5 !important;
    color: #333 !important;
  }
}
</style> 